#include <iostream>
#include <memory.h>

using namespace std;

/*this joseph only takes O(n) time, which is much faster than mine version.
 * need to scrutize later
 * dynamic programming:
 * observations:
 * 1) if we shift the ids by k, namely, start from k instead of 0, we should add the result by k%n
 * 2) after the first round, we start from k+1 ( possibly % n) with n-1 elements, that is equal to 
 *    an (n-1) problem while start from (k+1)th element instead of 0, so the answer is (f(n-1, m)+k+1)%n
 * 3) k = m-1, so f(n,m)=(f(n-1,m)+m)%n. 
 * 4) finally, f(1, m) = 0;
 * reference link: http://blog.csdn.net/v_july_v/article/details/6870251
 */

int joseph(int n, int m) {
  int fn=0;
  for (int i=2; i<=n; i++) {
    fn = (fn+m)%i;  }
  return fn;
}

int main()
{
	int n,m;
	while(cin>>n>>m) {
		if (n <= 0)
			continue;
		if (n == 1) {
			cout << 0 << endl;
			continue;
		}

		int * array = new int[n];
		memset(array, 0, sizeof(int)*n);
		int k = 0;	//starting from index 0
		int count = 0;	//the number of numbers deleted.
		while(count < n-1) {
			int s = 0;
			for (;; k = (k + 1)%n) {
				if (array[k] == 0) {
					if (++s == m) {
						array[k] = 1;
						break;
					}
				}
			}
			
			count++;
		}

		for(int i = 0; i < n; ++i) {
			if (array[i] == 0) {
				cout << i << endl;
			}
		}

		cout << "joseph: " << joseph(n,m) << endl;
	}
	return 0;
}
